#include "http_response.h"

HttpResponse::HttpResponse(bool close)
    : m_statusCode(kUnknown)
    , m_closeConnection(close)
    , m_corsStatus(true)
{

}

/**
 * @brief HttpResponse::appendToBuffer 输出HTTP响应数据到output
 * @param output 用于写入的变量
 */
void HttpResponse::appendToBuffer(QByteArray &output) const
{
    output.clear();

    // 设置协议和版本号
    QString buf = QString("HTTP/1.1 %1 ").arg(m_statusCode);
    output.append(buf.toUtf8());
    output.append(m_statusMessage);
    output.append("\r\n");

    // 设置Content-Length 字段
    buf = QString("Content-Length: %1\r\n").arg(m_body.length());
    output.append(buf.toUtf8());
    if (!m_closeConnection) {
      output.append("Connection: Keep-Alive\r\n");
    } else {
      output.append("Connection: close\r\n");
    }

    // 处理设置的头部字段
    for (const auto &header : m_headers.keys()) {
      output.append(header);
      output.append(": ");
      output.append(m_headers[header]);
      output.append("\r\n");
    }

    // 处理XMLHttpRequest的CORS
    if (m_corsStatus) {
        output.append("Access-Control-Allow-Origin: *\r\n");
        output.append("Access-Control-Allow-Methods: GET, POST, OPTIONS\r\n");
        output.append("Access-Control-Allow-Headers: *\r\n");
        output.append("Allow: GET, POST, OPTIONS\r\n");
    }

    output.append("\r\n");
    // 写入HTTP消息体内容
    output.append(m_body, static_cast<int>(m_body.length()));
}

/**
 * @brief HttpResponse::makeTextResponse 构造一个文本类型的HTTP响应报文
 * @param code 响应码
 * @param message body的数据
 * @param closeStatus 设置Connection 类型, true -> close ,false -> Keep-Alive
 * @return 返回构造的数据
 */
QByteArray HttpResponse::makeTextResponse(HttpStatusCode code, const QByteArray &message, bool closeStatus)
{
    HttpResponse response;
    response.setContentType("text/plain;charset=UTF-8");
    response.setStatusCode(code);
    response.setStatusMessage(statusCodeToString(code).toUtf8());
    response.setBody(message);
    response.setCloseConnection(closeStatus);
    QByteArray buffer;
    response.appendToBuffer(buffer);
    return buffer;
}

/**
 * @brief HttpResponse::makeJsonResponse 构造一个json类型的HTTP响应报文
 * @param code 状态码
 * @param message body的数据
 * @param closeStatus 设置Connection 类型, true -> close ,false -> Keep-Alive
 * @return 返回构造的数据
 */
QByteArray HttpResponse::makeJsonResponse(HttpStatusCode code, const QByteArray &message, bool closeStatus)
{
    HttpResponse response;
    response.setContentType("application/json;charset=UTF-8");
    response.setStatusCode(code);
    response.setStatusMessage(statusCodeToString(code).toUtf8());
    response.setBody(message);
    response.setCloseConnection(closeStatus);
    QByteArray buffer;
    response.appendToBuffer(buffer);
    return buffer;
}

/**
 * @brief HttpResponse::makeNotFoundResponse 构造一个 404 Not Found 页面
 * @return 返回一个显示404 Not Found 的HTML
 */
QByteArray HttpResponse::makeNotFoundResponse()
{
    QString notFoundHtml =
    "<!DOCTYPE html>\n"
    "<html>\n"
    "<head>\n"
        "<title>SSO Server</title>\n"
    "</head>\n"
    "<body>\n"
        "<h1>404 Not Found</h1>\n"
    "</body>\n"
    "</html>\n";

    HttpResponse response;
    response.setContentType("text/html;charset=UTF-8");
    response.setStatusCode(k404NotFound);
    response.setStatusMessage(statusCodeToString(k404NotFound).toUtf8());
    response.setBody(notFoundHtml.toUtf8());
    response.setCloseConnection(true);
    QByteArray buffer;
    response.appendToBuffer(buffer);
    return buffer;
}

/**
 * @brief HttpResponse::statusCodeToString 状态码转换为可读的字符串
 * @param statusCode 状态码
 * @return 返回状态码字符串
 */
QString HttpResponse::statusCodeToString(HttpStatusCode statusCode)
{
    switch (statusCode) {
    case k200Ok:
        return "OK";
    case k400BadRequest:
        return "Bad Request";
    case k403Forbidden:
        return "Forbidden";
    case k404NotFound:
        return "Not Found";
    default:
        return "Unknown";
    }
}
